<template>
  <el-dialog v-model="uploadDialogVisible" title="上传图片识别出库" :width="widths" :before-close="closeUploadDialog">
    <div class="upload-container">
      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" class="steps-container">
        <el-step title="上传图片" description="选择并上传图片" />
        <el-step title="识别结果" description="查看识别结果" />
      </el-steps>

      <!-- 步骤内容区域 -->
      <div class="step-content">
        <!-- 步骤1: 上传图片 -->
        <div v-if="activeStep === 0" class="step-upload">
          <el-upload
            class="image-uploader"
            :action="apiUrl"
            :file-list="fileList"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            :on-exceed="handleExceed"
            :on-success="handleSuccess"
            :on-error="handleError"
            :headers="UploadHeaders"
            :data="UploadData"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
          >
            <template #default>
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
            </template>
          </el-upload>

          <!-- 图片预览区域 -->
          <div v-if="previewUrl" class="preview-container">
            <h4>图片预览</h4>
            <img :src="previewUrl" class="preview-image" />
          </div>
        </div>

        <!-- 步骤2: 识别结果 -->
        <div v-if="activeStep === 1" class="step-result">
          <!-- 识别结果区域 -->
          <div v-if="tableData.length > 0" class="recognition-result">
            <h4>识别结果</h4>
            <el-form :inline="true" size="large">
              <el-form-item label="企业" label-width="80px" class="custom-label">
                <el-autocomplete
                  v-model="state"
                  :fetch-suggestions="querySearchAsync"
                  value-key="company_name"
                  placeholder="请输入"
                  @select="handleSelect"
                />
              </el-form-item>
              <el-form-item label="业务员" label-width="80px">
                <el-select v-model="uid" placeholder="请选择">
                  <el-option v-for="item in listData" :key="item.id" :label="item.nickname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-form>
            <div class="heads2">
              <div class="bolck">
                <el-button type="primary" @click="setAllOutInvoicings(1)">一键开票</el-button>
                <el-button type="primary" @click="setAllOutInvoicings(2)">取消开票</el-button>
              </div>
              <div class="bolck">
                <el-button type="primary" @click="setAllOutChecks(1)">一键先款先票</el-button>
                <el-button type="primary" @click="setAllOutChecks(2)">取消先款先票</el-button>
              </div>
              <div class="bolck">
                <el-date-picker
                  v-model="value2"
                  type="datetime"
                  placeholder="请选择"
                  :shortcuts="shortcuts"
                  :format="customDateTimeFormat"
                  :value-format="customDateTimeFormat"
                  @change="handleDateChange"
                />
              </div>
            </div>
            <vxe-table
              border
              show-overflow
              :data="tableData"
              show-footer
              :column-config="{ resizable: true }"
              :edit-config="{ trigger: 'click', mode: 'cell' }"
              :footer-method="footerMethod"
            >
              <vxe-column type="seq" width="60" />
              <vxe-column field="acceptorName" title="承兑人" />
              <vxe-column field="billAmount" title="票面金额" width="180" />
              <vxe-column field="expirationDate" title="到期日" width="180" />
              <vxe-column field="billNo" title="票号" width="180" />
              <vxe-column
                field="out_price"
                title="每十万价格"
                :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.out_price" @input="handleInput(row)" type="number" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column
                field="out_discount"
                title="贴息费"
                :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input
                    v-model="row.out_discount"
                    @input="handleDiscount(row)"
                    type="number"
                    placeholder="请输入"
                  />
                </template>
              </vxe-column>
              <vxe-column
                field="out_finally"
                title="实付金额"
                :edit-render="{ name: 'input', attrs: { type: 'number', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-input v-model="row.out_finally" @input="handleFinally(row)" type="number" placeholder="请输入" />
                </template>
              </vxe-column>
              <vxe-column field="out_time" title="出库时间" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input v-model="row.out_time" type="datetime" placeholder="请选择出库时间" transfer />
                </template>
              </vxe-column>
              <vxe-column field="out_invoicings" title="开票" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ formatSex(row.out_invoicings) }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-select v-model="row.out_invoicings" transfer>
                    <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
                  </vxe-select>
                </template>
              </vxe-column>
              <vxe-column field="out_checks" title="先款先票" :edit-render="{}">
                <template #default="{ row }">
                  <span>{{ formatSex(row.out_checks) }}</span>
                </template>
                <template #edit="{ row }">
                  <vxe-select v-model="row.out_checks" transfer>
                    <vxe-option v-for="item in sexList1" :key="item.value" :value="item.value" :label="item.label" />
                  </vxe-select>
                </template>
              </vxe-column>
              <vxe-column
                field="remark"
                title="备注"
                :edit-render="{ name: 'textarea', attrs: { type: 'textarea', placeholder: '请输入' } }"
              >
                <template #edit="{ row }">
                  <vxe-textarea v-model="row.remark" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }" />
                </template>
              </vxe-column>
              <vxe-column title="操作" width="100">
                <template #default="{ rowIndex }">
                  <el-button type="danger" size="small" @click="handleDeleteRow(rowIndex)">删除</el-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div v-else class="no-result">
            <el-empty description="暂无识别结果，请返回上一步上传图片" />
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeUploadDialog">取消</el-button>
        <el-button v-if="activeStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="activeStep < 1" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="activeStep === 1" type="primary" @click="confirmUpload">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 图片预览弹窗 -->
  <el-dialog v-model="previewVisible" title="图片预览">
    <img :src="previewUrl" alt="Preview Image" style="width: 100%" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue"
import { ElMessage } from "element-plus"
import { getToken } from "@/utils/cache/cookies"
// import { Plus } from "@element-plus/icons-vue"
import { generatePrice, generateDiscount, sumValuesForName } from "@/utils/common"
import { VxeTablePropTypes } from "vxe-table"
import Decimal from "decimal.js"
import { companyListApi } from "@/api/conventional"
import { getAdminRoleListApi } from "@/api/system"
import { doBatchSellApi } from "@/api/billv2"

const widths = ref("50%")
// 上传API地址
const apiUrl = import.meta.env.VITE_BASE_API + "/Ocr/recognizeGeneral"
const UploadHeaders = {
  "X-Token": getToken()
}

// 上传数据对象，包含固定的type参数
const UploadData = {
  type: "buy"
}

// Emits 定义返回事件
const emit = defineEmits(["recognition-complete", "upload-close"])

// 控制上传弹框
const uploadDialogVisible = ref(false)
const previewVisible = ref(false)

// 当前调用方的标识符
const currentContextKey = ref<string>("")

// 上传文件列表
const fileList = ref<any[]>([])
const fileLists = ref<any[]>([])

// 当前预览图片的 URL
const previewUrl = ref("")

// 识别结果
const recognitionResult = ref<Record<string, string> | null>(null)

// 表格数据
const tableData = ref<any[]>([])

// 企业和业务员相关
const listData = ref<any>([])
const state = ref("")
const uid = ref<number>(0)
const company_id = ref<number>(0)

// 是/否选项列表
const sexList1 = ref([
  { label: "是", value: 1 },
  { label: "否", value: 2 }
])

// 格式化是/否显示
const formatSex = (value: number) => {
  if (value === 1) {
    return "是"
  }
  if (value === 2) {
    return "否"
  }
  return ""
}

// 表格底部统计方法
const footerMethod: VxeTablePropTypes.FooterMethod<any> = ({ columns, data }) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "统计"
      }
      if (["billAmount", "out_discount", "out_finally"].includes(column.field)) {
        return sumValuesForName(data, column.field)
      }

      return null
    })
  ]
}

// 日期选择相关
const value2 = ref("")
const customDateTimeFormat = ref<string>("YYYY-MM-DD HH:mm:ss")
const shortcuts = [
  {
    text: "今天",
    value: new Date()
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 1)
      return date
    }
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date()
      date.setDate(date.getDate() - 7)
      return date
    }
  }
]

// 步骤控制
const activeStep = ref(0) // 当前激活的步骤，0表示第一步，1表示第二步

// 打开上传弹框，并传入调用方标识符
const openUploadDialog = (contextKey: string) => {
  currentContextKey.value = contextKey // 设置当前调用方标识符
  uploadDialogVisible.value = true
  activeStep.value = 0 // 重置为第一步
  widths.value = "50%"

  // 加载业务员列表
  getAdminList()
}
defineExpose({ openUploadDialog })

// 关闭上传弹框
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
  resetUploadDialog() // 重置弹框数据
  // 触发取消事件，传递当前 contextKey
  emit("upload-close", currentContextKey.value)
}

// 重置上传弹框的状态
const resetUploadDialog = () => {
  fileList.value = [] // 清空文件列表
  currentContextKey.value = "" // 清空调用方标识符
  previewUrl.value = "" // 清空预览 URL
  recognitionResult.value = null // 清空识别结果
  tableData.value = [] // 清空表格数据
  activeStep.value = 0 // 重置步骤为第一步
  state.value = "" // 清空企业
  uid.value = 0 // 清空业务员
  company_id.value = 0 // 清空企业ID
}

// 下一步
const nextStep = () => {
  if (activeStep.value === 0 && tableData.value.length === 0) {
    ElMessage.warning("暂无识别结果，请先上传并识别图片")
    return
  }
  widths.value = "98%"
  activeStep.value++
}

// 上一步
const prevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value--
    widths.value = "50%"
  }
}

// 获取业务员列表
const getAdminList = async () => {
  await getAdminRoleListApi({
    role_ids: 2
  })
    .then((res) => {
      listData.value = res.data
    })
    .catch(() => {})
    .finally(() => {})
}

// 企业搜索
const querySearchAsync = (queryString: string, cb: (arg: any) => void) => {
  state.value = queryString
  companyListApi({
    company_name: state.value
  }).then((res) => {
    const lists = res.data
    if (lists.length == 0) {
      ElMessage.error("请先添加企业信息")
      cb([])
    } else {
      cb(lists)
    }
  })
}

// 企业选择处理
const handleSelect = (item: any) => {
  uid.value = item.uid
  company_id.value = item.id
}

// 确认上传操作
const confirmUpload = async () => {
  // 由于只有在第二步且有表格数据时才能点击确定按钮，所以不需要再检查tableData

  // 检查是否选择了企业和业务员
  if (company_id.value === 0) {
    ElMessage.warning("请选择企业")
    return
  }

  if (uid.value === 0) {
    ElMessage.warning("请选择业务员")
    return
  }

  try {
    console.log(tableData.value)
    // 调用批量出库API
    await doBatchSellApi({
      out_company_id: company_id.value,
      out_admin_id: uid.value,
      batch_list: tableData.value
    })
    ElMessage.success("操作成功")

    emit("upload-close", currentContextKey.value)
    resetUploadDialog() // 重置弹框数据
    uploadDialogVisible.value = false
  } catch (error) {
    ElMessage.error("操作失败，请重试")
  }
}

// 删除图片
const handleRemove = () => {
  ElMessage.success("图片已删除")
  previewUrl.value = "" // 清空预览 URL
  recognitionResult.value = null // 清空识别结果
}

// 上传成功
const handleSuccess = (response: any) => {
  ElMessage.success("图片上传成功")

  // 检查返回的数据格式
  if (response.code === 200 && response.data && response.data.data && response.data.data.length > 0) {
    // 直接使用返回的数据填充表格
    tableData.value = response.data.data.map((item: any) => ({
      bill_id: item.bill_id,
      acceptorName: item.acceptorName,
      billAmount: item.billAmount,
      expirationDate: item.expirationDate,
      billNo: item.billNo,
      out_price: item.out_price || "",
      out_discount: item.out_discount || "",
      out_finally: item.out_finally || "",
      out_time: item.out_time || "",
      out_invoicings: item.out_invoicings || 2, // 默认否
      out_checks: item.out_checks || 2, // 默认否
      remark: ""
    }))

    // 识别完成后自动进入下一步
    nextStep()
  } else {
    // 如果没有识别结果数据，则使用原来的模拟方式
    // 更新 fileList
    fileLists.value = response.data

    // 设置预览URL
    if (response.data && response.data.length > 0) {
      previewUrl.value = response.data[0].url

      // 模拟图片识别过程
      ElMessage.info("正在识别图片...")
    }
  }
}

// 处理价格输入
const handleInput = (row: any) => {
  const { finallyAmount, discountAmount } = generatePrice(
    row.out_price,
    row.out_finally,
    row.out_discount,
    row.billAmount,
    false
  )
  row.out_finally = finallyAmount
  row.out_discount = discountAmount
}

// 处理贴息费输入
const handleDiscount = (row: any) => {
  const { price, finallyAmount } = generateDiscount(
    row.out_price,
    row.out_finally,
    row.out_discount,
    row.billAmount,
    false
  )
  row.out_price = price
  row.out_finally = finallyAmount
}

// 处理实付金额输入
const handleFinally = (row: any) => {
  const billAmount = new Decimal(row.billAmount).times(10000)
  const out_finally = new Decimal(row.out_finally)
  const discountAmount = billAmount.minus(out_finally).toNumber()
  const { price } = generateDiscount(row.out_price, row.out_finally, discountAmount, billAmount.toString(), true)
  row.out_price = price.toFixed(2)
  row.out_discount = discountAmount
}

// 批量设置开票状态
const setAllOutInvoicings = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.out_invoicings = value
  })
}

// 批量设置先款先票状态
const setAllOutChecks = (value: number) => {
  tableData.value.forEach((row: any) => {
    row.out_checks = value
  })
}

// 批量设置日期
const handleDateChange = (value: any) => {
  tableData.value.forEach((row: any) => {
    row.out_time = value
  })
}

// 删除行
const handleDeleteRow = (rowIndex: number) => {
  if (rowIndex >= 0 && rowIndex < tableData.value.length) {
    tableData.value.splice(rowIndex, 1)
    ElMessage.success("行数据已删除")
  }
}

// 上传失败
const handleError = (error: any, file: any, fileList: any[]) => {
  ElMessage.error("图片上传失败")
  // 从 fileList 中移除失败的文件
  const index = fileList.findIndex((item) => item.uid === file.uid)
  if (index !== -1) {
    fileList.splice(index, 1)
  }
}

// 上传前校验图片
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith("image/")
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error("上传文件必须是图片格式!")
    return false
  }
  if (!isLt5M) {
    ElMessage.error("上传图片大小不能超过 5MB!")
    return false
  }
  return true
}

// 超出限制处理
const handleExceed = () => {
  ElMessage.warning("最多只能上传 1 张图片")
}

// 预览图片
const handlePreview = (file: any) => {
  previewUrl.value = file.url
  previewVisible.value = true
}
</script>

<style scoped lang="scss">
.upload-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.steps-container {
  margin-bottom: 30px;
}

.step-content {
  min-height: 300px;
  padding: 20px 0;
}

.step-upload,
.step-result {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.image-uploader {
  text-align: center;
  width: 100%;
}

.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
:deep(.el-upload-list) {
  width: 100%;
}

.el-upload-dragger {
  width: 100%;
  height: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.el-icon--upload {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.preview-container {
  margin-top: 20px;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.recognition-result {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #f8f9fa;
}

.no-result {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.heads {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads div {
  margin-left: 10px;
}

.heads2 {
  display: flex;
  justify-content: end;
  margin-bottom: 10px;
}

.heads2 .bolck {
  margin-left: 10px;
}

.custom-label {
  font-weight: bold;
  color: #000;
}
</style>
<style scoped>
/* 在 scoped 样式中使用 /deep/ 选择器穿透样式隔离 */
:deep(.el-form-item__label) {
  color: red;
  font-weight: bold;
  font-size: 20px;
  /* 添加其他自定义样式 */
}
</style>
